package src.main.zuhe;

import java.util.ArrayList;
import java.util.List;
/**安全组合模式的写法*/
public class Test2 {
    public static void main(String[] args) {

        System.out.println("============安全组合模式===========");

        File qq = new File("QQ.exe");
        File wx = new File("微信.exe");

        Folder office = new Folder("办公软件",2);

        File word = new File("Word.exe");
        File ppt = new File("PowerPoint.exe");
        File excel = new File("Excel.exe");

        office.add(word);
        office.add(ppt);
        office.add(excel);

        Folder wps = new Folder("金山软件",3);
        wps.add(new File("WPS.exe"));
        office.add(wps);

        Folder root = new Folder("根目录",1);
        root.add(qq);
        root.add(wx);
        root.add(office);

        System.out.println("----------show()方法效果-----------");
        root.show();//关联所有节点的方法

        System.out.println("----------list()方法效果-----------");
        root.list();
        System.out.println("----------get()方法效果-----------");
        System.out.println(root.get(2).name);
        System.out.println(root.get(0).name);

        System.out.println("----------show()方法效果-----------");
        root.get(2).show();
    }
}
/**根*/
abstract class Directory {
    protected String name;
    public Directory(String name) {
        this.name = name;
    }
    public abstract void show();

}
/**叶子结点*/
class File extends Directory {
    public File(String name) {
        super(name);
    }
    @Override
    public void show() {
        System.out.println(this.name);
    }
}
/**树枝节点*/
class Folder extends Directory {
    private List<Directory> dirs;
    private Integer level;
    public Folder(String name,Integer level) {
        super(name);
        this.level = level;
        this.dirs = new ArrayList<Directory>();
    }

    @Override
    public void show() {
        System.out.println(this.name);
        for (Directory dir : this.dirs) {
            //控制显示格式
            if(this.level != null){
                for(int  i = 0; i < this.level; i ++){
                    //打印空格控制格式
                    System.out.print("  ");
                }
                for(int  i = 0; i < this.level; i ++){
                    //每一行开始打印一个+号
                    if(i == 0){ System.out.print("+"); }
                    System.out.print("-");
                }
            }
            //打印名称
            dir.show();
        }
    }

    public boolean add(Directory dir) {
        return this.dirs.add(dir);
    }

    public boolean remove(Directory dir) {
        return this.dirs.remove(dir);
    }

    public Directory get(int index) {
        return this.dirs.get(index);
    }

    public void list(){
        for (Directory dir : this.dirs) {
            System.out.println(dir.name);
        }
    }

}


